# -*- coding: utf-8 -*-
class LoanDeliveryController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:editDeliveryFromLoan,:auditLoanDeliveryForCancel,:getProductsForEdit,:hxListForLoanDelivery,:newDeliveryFromLoan,:editDeliveryFromLoan,:auditLoanDelivery,:loan_delivery_print_header,:loan_delivery_print_content,:loan_delivery_print_footer]

  #出库单的列表页面
  def loanDeliveryList

  end

  #出库审批列表
  def loanDeliveryAuditList

  end

  #显示借货订单转换为出库单的页面
  def newDeliveryFromLoan

  end

  #编辑转换自己借货订单的出库单。
  def editDeliveryFromLoan
    @loanId = LoanDelivery.find(params[:id]).loan_id
  end

  #直接使用出库单的方式，暂时不用。
  def create
    paramsHash = Util.paramsPreprocesseToHash(params[:data])

    #productHash = paramsHash["products"][0]
    #取得这次入库，到入到哪个库中。
    loanDelivery = LoanDelivery.new
    loanDelivery.company_id = session[:company_id]
    loanDelivery.department_id = session[:department_id]
    loanDelivery.employee_id = session[:employee_id]
    loanDelivery.action_date = paramsHash['action_date']
    loanDelivery.customer_id = paramsHash['customer_id']
    loanDelivery.warehouse_id = paramsHash['warehouse_id']
    #loanDelivery.to_warehouse_id = paramsHash['to_warehouse_id']
    #插入products信息
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      loanDeliveryDetail = LoanDeliveryDetail.new
      loanDeliveryDetail.product_id = productHash["product_id"]
      loanDeliveryDetail.quantity = productHash["quantity"]
      loanDelivery.loan_delivery_details << loanDeliveryDetail
    end
    loanDelivery.save
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #经过变更修改后，提交此方法
  def update
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    #productHash = paramsHash["products"][0]
    loanDelivery = LoanDelivery.find(:first,:conditions=>["id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status not like ?)",paramsHash['id'],session[:company_id],'%撤消%'])
    if loanDelivery != nil
      #如果在保存时，有人编辑过，则不能保证
      if loanDelivery.lock_version > paramsHash['lock_version'].to_i
        info="有其它用户在您保存之前编辑过此借货出库单记录，请从新编辑！"
        result = "{success:true,info:'#{info}'}"
        render :text=>result, :layout=>false and return false
      end
      
      #生成历史记录
      loanDeliveryHx = LoanDeliveryHx.new
      loanDeliveryHx.company_id = loanDelivery.company_id
      loanDeliveryHx.department_id = loanDelivery.department_id
      loanDeliveryHx.employee_id = loanDelivery.employee_id
      loanDeliveryHx.loan_delivery_id = loanDelivery.id
      loanDeliveryHx.loan_id = loanDelivery.loan_id
      loanDeliveryHx.warehouse_id = loanDelivery.warehouse_id
      loanDeliveryHx.action_date = loanDelivery.action_date
      loanDeliveryHx.linkman = loanDelivery.linkman
      loanDeliveryHx.phone = loanDelivery.phone
      loanDeliveryHx.delivery_address = loanDelivery.delivery_address
      
      loanDelivery.company_id = session[:company_id]
      loanDelivery.department_id = session[:department_id]
      loanDelivery.employee_id = session[:employee_id]
      loanDelivery.warehouse_id = paramsHash['warehouse_id']
      loanDelivery.action_date = paramsHash['action_date']
      loanDelivery.description = paramsHash['description']
      loanDelivery.linkman = paramsHash['linkman']
      loanDelivery.phone = paramsHash['phone']
      loanDelivery.delivery_address = paramsHash['delivery_address']
      
      loanDelivery.audit_opinion = ''
      loanDelivery.auditor_id = ''

      if paramsHash['temporary'] == '1'
        loanDelivery.deal_with_status = Constants::TEMP_ADD
      else
        loanDelivery.deal_with_status = ""
        loanDelivery.auditing_status = Constants::AUDIT_APPLY_ADD
      end

      #products信息
      productsHashArray = paramsHash["products"]
      #在这里，要作一个增，删，编辑操作，以前台数据为准。
      #首先各取出前台与后台的ID数组
      fgIdArray = Array.new
      productsHashArray.each do |productHash|
        fgIdArray << productHash["id"].to_i
      end

      bgIdArray = Array.new
      loanDeliveryDetails = loanDelivery.loan_delivery_details
      loanDeliveryDetails.each do |loanDeliveryDetail|
        bgIdArray << loanDeliveryDetail.id
        #借助这些循环保存历史记录
        #变更后，记录变更过程
        loanDeliveryHxDetail = LoanDeliveryHxDetail.new
        loanDeliveryHxDetail.product_id = loanDeliveryDetail.product_id
        loanDeliveryHxDetail.quantity = loanDeliveryDetail.quantity
        loanDeliveryHx.loan_delivery_hx_details << loanDeliveryHxDetail
      end

      idIntersectionArray = fgIdArray & bgIdArray
      addIdArray = fgIdArray - idIntersectionArray
      delIdArray = bgIdArray - idIntersectionArray
      LoanDeliveryDetail.delete(delIdArray)

      #更新前，把汇总表中相关数据全删除了，在后面的步骤中再添加。
      ProductCollection.delete_all(["resource_type = 'LoanDelivery' AND resource_id = ?",loanDelivery.id])
      #生成历史记录
      loanDeliveryHx.seq_number = loanDelivery.seq_number
      loanDeliveryHx.order_number = loanDelivery.order_number
      loanDeliveryHx.deal_with_status = loanDelivery.deal_with_status
      loanDeliveryHx.auditing_status = loanDelivery.auditing_status
      loanDeliveryHx.auditor_id = loanDelivery.auditor_id
      loanDeliveryHx.audit_opinion = loanDelivery.audit_opinion
      loanDeliveryHx.customer_id = loanDelivery.customer_id

      productsHashArray.each do |productHash|
        #只有当用户选择的产品不为空时，才有详细订单。
        if productHash["product_id"] !=""
          #没Id说明是新增加的。
          if productHash["id"] == ""
            loanDeliveryDetail = LoanDeliveryDetail.new
            loanDeliveryDetail.product_id = productHash["product_id"]
            loanDeliveryDetail.quantity = productHash["quantity"]
            loanDeliveryDetail.description = productHash["description"]
            loanDelivery.loan_delivery_details << loanDeliveryDetail
          else
            loanDeliveryDetail = LoanDeliveryDetail.find(productHash["id"].to_i)
            loanDeliveryDetail.product_id = productHash["product_id"]
            loanDeliveryDetail.quantity = productHash["quantity"]            
            loanDeliveryDetail.description = productHash["description"]
            loanDeliveryDetail.save
          end
          #同时生成结算表的内容。
          productCollection = ProductCollection.new
          productCollection.company_id = loanDelivery.company_id
          productCollection.department_id = loanDelivery.department_id
          productCollection.employee_id = loanDelivery.employee_id
          productCollection.customer_id = loanDelivery.customer_id
          productCollection.warehouse_id = loanDelivery.warehouse_id

          productCollection.product_id = loanDeliveryDetail.product_id
          productCollection.quantity = 0 - loanDeliveryDetail.quantity
          productCollection.description =  loanDeliveryDetail.description
          productCollection.resource_id =  loanDelivery.id
          productCollection.resource_type =  LoanDelivery.name
          productCollection.action_date =  loanDelivery.action_date
          productCollection.save!

        end
      end
      loanDelivery.save!
      loanDeliveryHx.save!
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getAllLoanDelivery
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:order_number].to_s != ''
      conditionsStr = 'seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:customer_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'customer_id = :customer_id'
      else
        conditionsStr = conditionsStr+' AND customer_id = :customer_id'
      end
      conditionsHash[:customer_id] = params[:customer_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    if params[:loan_number].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'loans.seq_number in (:loan_number)'
      else
        conditionsStr = conditionsStr+' AND loans.seq_number in (:loan_number)'
      end
      conditionsHash[:loan_number] = params[:loan_number].split(/,/)
    end

    count = LoanDelivery.countAllDelivery conditionsStr,conditionsHash
    deliveries = LoanDelivery.findAllDelivery conditionsStr,conditionsHash,paramsHash

    jsonStr="{totalProperty:"+count.to_s+",root:"+deliveries.to_json(:include=>[:employee,:department,:warehouse,:customer,:loan])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到某个出库单的信息
  def getLoanDeliveryById
    loanDelivery = LoanDelivery.find(params[:id],:include=>[:customer])
    rootStr = loanDelivery.to_json(:include=>[:customer])
    jsonStr = "{root:["+rootStr+"]}"
    render :text=>jsonStr, :layout=>false
  end

  #得到出库单的详细信息
  def getLoanDeliveryDetailsById
    loanDeliveryDetails = LoanDeliveryDetail.find_all_by_loan_delivery_id(params[:loan_delivery_id])

    jsonStr="{totalProperty:"+loanDeliveryDetails.length.to_s+",root:"+loanDeliveryDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec,:number]}})+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到出库单的详细信息,及可出库与数存，以用于编辑，所以对于不用的记录，一定要撤消，不然数量不准。
  def getLoanDeliveryDetailsBalanceById
    loanDeliveryDetails = LoanDeliveryDetail.find_all_by_loan_delivery_id(params[:loan_delivery_id])

    jsonStr="{totalProperty:"+loanDeliveryDetails.length.to_s+",root:"+loanDeliveryDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec]}})+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #取得要审批的出库单
  def getAllLoanDeliveryByAuditStatus
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = "loan_deliveries.auditing_status like :auditing_status"
    conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"

    if params[:order_number].to_s != ''
      conditionsStr = 'loan_deliveries.order_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:customer_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'loan_deliveries.customer_id = :customer_id'
      else
        conditionsStr = conditionsStr+' AND loan_deliveries.customer_id = :customer_id'
      end
      conditionsHash[:customer_id] = params[:customer_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'loan_deliveries.action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND loan_deliveries.action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'loan_deliveries.action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND loan_deliveries.action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    if params[:loan_number].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'loans.seq_number in (:loan_number)'
      else
        conditionsStr = conditionsStr+' AND loans.seq_number in (:loan_number)'
      end
      conditionsHash[:loan_number] = params[:loan_number].split(/,/)
    end

    count = LoanDelivery.countAllDelivery conditionsStr,conditionsHash
    deliveries = LoanDelivery.findAllDelivery conditionsStr,conditionsHash,paramsHash

    jsonStr="{totalProperty:"+count.to_s+",root:"+deliveries.to_json(:include=>[:employee,:department,:warehouse,:customer,:loan])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #查出属于某个借货订单的所有出库单
  def getLoanDeliverysByLoanId
    loanDeliverys = LoanDelivery.find(:all,:conditions=>["loan_id = ?",params[:id]])

    jsonStr="{totalProperty:"+loanDeliverys.length.to_s+",root:"+loanDeliverys.to_json(:include=>[:employee,:department,:warehouse,:customer,:loan])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #此方法作了调整，不用进行整单的转换，用户可对借货单进行调整，然后再保存，即一个借货单可对应多个出库单
  def transformLoanIntoDelivery
    paramsHash = Util.paramsPreprocesseToHash(params[:data])

    loanId = paramsHash['loan_id']
    warehouseId = paramsHash['warehouse_id']

    loan =  Loan.find(loanId)
    
    if loan.auditing_status == Constants::PASS_APPLY_CANCEL
      info = "已经撤消的借货订单，不可以再转换为出库单！"
    elsif  loan.auditing_status == Constants::AUDIT_APPLY_EDIT
      info = "借货订单的状态为:申请变更，不可以再转换为出库单！"
    elsif  loan.store_status == Constants::FINISH_DELIVERY
      info = "已经出库完毕的借货订单，不可以再转换为出库单！"
    else
      loanDelivery = LoanDelivery.new
      loanDelivery.loan_id = loan.id
      loanDelivery.company_id = loan.company_id
      loanDelivery.department_id = loan.department_id
      loanDelivery.employee_id = loan.employee_id
      loanDelivery.action_date = paramsHash['action_date']
      loanDelivery.customer_id = loan.customer_id
      loanDelivery.warehouse_id = warehouseId
      loanDelivery.linkman = paramsHash['linkman']
      loanDelivery.phone = paramsHash['phone']
      loanDelivery.delivery_address = paramsHash['delivery_address']
      
      if paramsHash['temporary'] == '1'
        loanDelivery.deal_with_status = Constants::TEMP_ADD
      else
        loanDelivery.auditing_status = Constants::AUDIT_APPLY_ADD
      end
      loanDelivery.save!  #先行保存一下，以便生成ID
      loan.store_status = Constants::DELIVERING
      #为了在进行结算表操作时提前获取ID，这时要提前存储purchaseOrder


      #向详细表中插入products信息
      productsHashArray = paramsHash["products"]
      productsHashArray.each do |productHash|
        #如果不为空则加入
        if productHash["product_id"] !=""
          #得到采购订单的详细价格，只有取出它的详细记录来。
          loanDeliveryDetail = LoanDeliveryDetail.new
          loanDeliveryDetail.product_id = productHash["product_id"]
          loanDeliveryDetail.quantity = productHash["quantity"]
          loanDeliveryDetail.description = productHash["description"]
          loanDelivery.loan_delivery_details << loanDeliveryDetail
          #为了实现占货功能，现在就要插入汇总表中数据。
          #同时生成结算表的内容。
          productCollection = ProductCollection.new
          productCollection.company_id = loanDelivery.company_id
          productCollection.department_id = loanDelivery.department_id
          productCollection.employee_id = loanDelivery.employee_id
          productCollection.customer_id = loanDelivery.customer_id
          productCollection.warehouse_id = warehouseId

          productCollection.product_id = loanDeliveryDetail.product_id
          productCollection.quantity = 0 - loanDeliveryDetail.quantity
          productCollection.description =  loanDeliveryDetail.description
          productCollection.resource_id =  loanDelivery.id
          productCollection.resource_type =  LoanDelivery.name
          productCollection.action_date =  loanDelivery.action_date
          productCollection.description =  loanDeliveryDetail.description
          productCollection.save!
        end
      end

      #在这儿再检查，对比一下借货订单与出库单的数量差，以确认要不要添加上“出库完毕”状态

      diffs = Loan.diff_loan_delivery(loanId)
      if diffs.length ==0
        loan.store_status = Constants::FINISH_DELIVERY
      end

      #开始事务，确保在流水号正常的情况下，保存入库单时,一但出现问题，则循环执行
      begin
        Sequence.transaction do
          #开始为借货订单取得流水号
          sequence = Sequence.find(:first,:conditions=>["company_id = ? AND sub_type = ?",session[:company_id],LoanDelivery.name])

          sequence.seq_no = sequence.seq_no + 1
          loanDelivery.seq_number = sequence.seq_no
          loanDelivery.order_number = sequence.ab + ":" + loanDelivery.seq_number.to_s + ":" + Date.today.to_s
          sequence.save!
          loanDelivery.save!
          #最后保存借货订单的状态更改。
          loan.save!
        end
      rescue ActiveRecord::StaleObjectError
        #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
        #这里特别指序号产生表。
        logger.info "somebody using sn before yours.............................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
        retry
      rescue ActiveRecord::RecordNotFound
        logger.info "RecordNotFound................................................................................"
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
      rescue Exception => e
        logger.info "logging......................................................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
        logger.info e
      end

      info = "成功"
    end

    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请撤消,如果系统设置不需要审批，则直接可以撤消。
  def applyToCancel
    begin
      loanDelivery = LoanDelivery.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_delivery_cancel == "否"
        loanDelivery.auditing_status = Constants::PASS_APPLY_CANCEL
        loanDelivery.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'LoanDelivery' AND resource_id = #{params[:id]}")
        #如果不需要审批，则把汇总表中的数据设置为is_locked = 1
      else
        loanDelivery.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      loanDelivery.auditor_id = session[:employee_id]
      loanDelivery.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #审批新增状态或变更状态。不论处理结果如何，都不对product_collections作处理了。因为之前的方法已经处理过了。
  def updateAuditingStatus
    loanDelivery = LoanDelivery.find(params[:id])
    info = nil
    if loanDelivery !=nil
      auditingStatus = params[:auditing_status]
      loanDelivery.auditor_id = session[:employee_id]
      loanDelivery.audit_opinion =  params[:audit_opinion]
      if(auditingStatus == "是")
        if loanDelivery.auditing_status == Constants::AUDIT_APPLY_EDIT
          auditingStatus = Constants::PASS_APPLY_EDIT
        else
          auditingStatus = Constants::PASS_APPLY_ADD
          loanDeliveryDetails = loanDelivery.loan_delivery_details
        end
        loanDelivery.auditing_status = auditingStatus
      else
        if loanDelivery.auditing_status == Constants::AUDIT_APPLY_EDIT
          auditingStatus = Constants::REJECT_APPLY_EDIT
        else
          auditingStatus = Constants::REJECT_APPLY_ADD
        end
        loanDelivery.auditing_status = auditingStatus
      end
      loanDelivery.auditor_id = session[:employee_id]
      loanDelivery.save!
      #结算表处理完毕。
      info = "成功"
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #根据审批的结果，处理借货订单，如果审批同意，则取消所有入库单。
  def updateAuditingCancelStatus
    loanDelivery = LoanDelivery.find(params[:id])
    loanDelivery.transaction do
      if params[:auditing_status]=='是'
        loanDelivery.auditing_status = Constants::PASS_APPLY_CANCEL
        loanDelivery.deal_with_status = Constants::CANCELED
        loanDelivery.audit_opinion = params[:audit_opinion]
        #删除汇总表中的所有数据。
        ProductCollection.delete_all(["resource_type = 'LoanDelivery' AND resource_id = ?",params[:id]])
      else
        loanDelivery.audit_opinion = params[:audit_opinion]
        loanDelivery.auditing_status = Constants::REJECT_APPLY_CANCEL
      end
      loanDelivery.auditor_id = session[:employee_id]
      loanDelivery.save!
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #审批出库单的预处理，提前抓出金额等供审批者参考。
  def auditLoanDelivery
  end

  #在编辑出库单时，判断可出库数量是多少。
  def getDetailsBalanceByIdForEdit
    loanDeliveryId = params[:id]
    loanDelivery = LoanDelivery.find(loanDeliveryId)

    loanDeliverys = LoanDelivery.find(:all,:select=>"dd.id,p.id as product_id,p.name as product_name,p.is_suit,p.number,p.spec,p.unit,dd.quantity,dd.description,newdd.quantity as dd_quantity,(ld.quantity - ifnull(newdd.quantity,0) + dd.quantity) as balance_quantity,pc.stock_quantity ",:joins =>"d
left join loan_delivery_details dd on d.id = dd.loan_delivery_id
left join (select loan_delivery_id,product_id,sum(quantity) as quantity
from loan_deliveries d left join loan_delivery_details dd on d.id = dd.loan_delivery_id
where d.loan_id = #{loanDelivery.loan_id} AND d.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newdd on newdd.product_id = dd.product_id
left join products p on p.id = dd.product_id
left join loan_details ld on ld.loan_id = d.loan_id and ld.product_id = dd.product_id and ld.is_locked = 0
left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 group by product_id) pc on pc.product_id = p.id
where d.id =  "+loanDeliveryId)

    jsonStr="{totalProperty:"+loanDeliverys.length.to_s+",root:"+loanDeliverys.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #在编辑时得到产品的信息，同时提供这个产品的现在可出库数量，未出库数量，库存数
  def getProductsForEdit
    loanId = params[:loan_id]
    #order_quantity是未转的数量，不代表可以转，因为有时候库存不足
    #总的思路就是显示可前本借货订单可转数，
    productIds = Array.new
    loanDetails = LoanDetail.find(:all,:conditions=>["loan_id = ? AND is_locked = 0",loanId])
    loanDetails.each do |loanDetail|
      productIds << loanDetail.product_id
    end
    loanDetails = LoanDetail.find(:all,:select=>"p.id,p.name,p.is_suit,p.number,p.spec,p.unit,ld.quantity - ifnull(newdd.quantity,0) as order_quantity,case when ld.quantity - ifnull(newdd.quantity,0) > ifnull(pc.stock_quantity,0) - ifnull(newdd.quantity,0) then ifnull(pc.stock_quantity,0) - ifnull(newdd.quantity,0) else ld.quantity - ifnull(newdd.quantity,0) END as balance_quantity,ifnull(pc.stock_quantity,0) as stock_quantity ",:joins =>"ld
left join (select loan_delivery_id,d.loan_id,product_id,sum(quantity) as quantity
from loan_deliveries d left join loan_delivery_details dd on d.id = dd.loan_delivery_id
where d.loan_id = "+loanId+" group by product_id) newdd on newdd.product_id = ld.product_id
left join products p on p.id = ld.product_id
left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 AND product_id in (#{productIds.join(",")}) group by product_id) pc on pc.product_id = p.id
where (ld.quantity - ifnull(newdd.quantity,0)) > 0 AND ld.loan_id =  "+loanId)

    jsonStr="{totalProperty:"+loanDetails.length.to_s+",root:"+loanDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到变更历史的摘要
  def getHxesById
    loanDeliveryHxes = LoanDeliveryHx.find_all_by_loan_delivery_id(params[:id],:include=>[:department,:employee,:warehouse])
    jsonStr="{totalProperty:"+loanDeliveryHxes.length.to_s+",root:"+loanDeliveryHxes.to_json(:include=>[:department,:employee,:warehouse])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据变更Id得到详细信息
  def getHxDetailsByHxId
    loanDeliveryHxDetails = LoanDeliveryHxDetail.find_all_by_loan_delivery_hx_id(params[:id],:include=>[:product])
    jsonStr="{totalProperty:"+loanDeliveryHxDetails.length.to_s+",root:"+loanDeliveryHxDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec]}})+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #生成打印销售凭证的头部
  def loan_delivery_print_header
    @loanDelivery = LoanDelivery.find(params[:id],:include=>[:loan,:department,:customer])

  end

  #生成打印销售凭证的内容
  def loan_delivery_print_content
    @loanDelivery = LoanDelivery.find(params[:id],:include=>[:loan_delivery_details,:loan,:customer])
    @loanDeliveryDetails = @loanDelivery.loan_delivery_details
    @totalQuantity = @loanDeliveryDetails.sum(:quantity)
    logger.info @totalQuantity
  end

  def loan_delivery_print_footer
    @loanDelivery = LoanDelivery.find(params[:id],:include=>[:loan_delivery_details,:customer])
  end
end
